package com.wgke.bluetooth;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Build;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.core.view.WindowCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wgke.bluetooth.db.CmdEntity;
import com.wgke.bluetooth.ui.BaseActivity;
import com.wgke.bluetooth.ui.Chart1Activity;
import com.wgke.bluetooth.ui.HeatMapActivity;
import com.wgke.bluetooth.ui.HomeActivity;
import com.wgke.bluetooth.ui.PressureVisualizationActivity;
import com.wgke.bluetooth.ui.RWActivity;
import com.wgke.bluetooth.utils.Actions;
import com.wgke.bluetooth.utils.Async;
import com.wgke.bluetooth.utils.CommonUtil;
import com.wgke.bluetooth.utils.FileUtil;
import com.wgke.bluetooth.utils.LogUtil;
import com.wgke.bluetooth.utils.SpUtil;
import com.wgke.bluetooth.vm.BaseVM;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends BaseActivity<BaseVM> implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {
    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;

    @Override
    public int layoutId() {
        return R.layout.activity_main;
    }


    @Override
    public void initView() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
            WindowInsetsController controller = getWindow().getInsetsController();
            if (controller != null) {
                controller.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        }
        surfaceView = findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

//        videoView = findViewById(R.id.videoView);
//        Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test);
//        videoView.setVideoURI(videoUri);
//        initializePlayer();

        boolean isFirst = SpUtil.getBool("version_code" + CommonUtil.getVersionCode(this), false);
        if (!isFirst) {
            Async.getInstance().await(() -> {
                Async.getInstance().getDao().deleteAll();
                String json = FileUtil.loadJsFromAssets("l5r5_2.json");
                Type userListType = new TypeToken<List<CmdEntity>>() {
                }.getType();
                Gson gson = new Gson();
                List<CmdEntity> data = gson.fromJson(json, userListType);
                assert data != null;
                Async.getInstance().getDao().insertAll(data.toArray(new CmdEntity[0]));
                SpUtil.put("version_code" + CommonUtil.getVersionCode(this), true);
            });
        }
    }

    @Override
    public void nextStep(int i) {
        postDelayed(1000, () -> {
            //startActivity(new Intent(this, RWActivity.class));
            startActivity(new Intent(this, HomeActivity.class));
            //startActivity(new Intent(this, HeatMapActivity.class));
            finish();
            LogUtil.saveLog("start app","next HomeActivity");
        });
        //FileUtil.convertDrawableToPng(this,R.drawable.ic_logo, "logo.png");
        //Actions.test3(this);
        //Actions.a001();
    }


    @Override
    public boolean isUseEventBus() {
        return false;
    }


    @Override
    public void onPrepared(MediaPlayer mp) {

        // 调整视频比例
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();
        float videoRatio = videoWidth / (float) videoHeight;

        int surfaceWidth = surfaceView.getWidth();
        int surfaceHeight = surfaceView.getHeight();
        float surfaceRatio = surfaceWidth / (float) surfaceHeight;

        // 获取显示区域尺寸
        int displayWidth = surfaceView.getWidth();
        int displayHeight = surfaceView.getHeight();

        // 计算缩放比例
        float widthRatio = (float) displayWidth / videoWidth;
        float heightRatio = (float) displayHeight / videoHeight;

        // 选择较大的缩放比例确保完全覆盖
        float scale = Math.max(widthRatio, heightRatio);

        // 计算缩放后的视频尺寸
        int scaledWidth = (int) (videoWidth * scale);
        int scaledHeight = (int) (videoHeight * scale);

        // 计算需要裁剪的偏移量
        int offsetX = (scaledWidth - displayWidth) / 2;
        int offsetY = (scaledHeight - displayHeight) / 2;

        // 应用矩阵变换
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        matrix.postTranslate(-offsetX, -offsetY);

        // 如果是TextureView
//        if (surfaceView instanceof TextureView) {
//            ((TextureView) surfaceView).setTransform(matrix);
//        }
        // 如果是SurfaceView需要特殊处理
        //else {
        // SurfaceView需要通过布局参数调整
        surfaceView.setLayoutParams(new FrameLayout.LayoutParams(scaledWidth, scaledHeight, Gravity.CENTER));

        // 然后通过父容器裁剪
        ViewGroup parent = (ViewGroup) surfaceView.getParent();
        parent.setClipChildren(true);
        //}


        mediaPlayer.start();
//        if (videoRatio > surfaceRatio) {
//            surfaceView.setLayoutParams(new FrameLayout.LayoutParams(
//                    FrameLayout.LayoutParams.MATCH_PARENT,
//                    (int) (surfaceWidth / videoRatio),
//                    Gravity.CENTER));
//        } else {
//            surfaceView.setLayoutParams(new FrameLayout.LayoutParams(
//                    (int) (surfaceHeight * videoRatio),
//                    FrameLayout.LayoutParams.MATCH_PARENT,
//                    Gravity.CENTER));
//        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDisplay(holder);

            // 设置视频源（放在res/raw目录下）
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.test);
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();

            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(mp -> {
                // 视频播放完成后跳转主界面

            });

            mediaPlayer.setLooping(true); // 循环播放
            mediaPlayer.prepareAsync(); // 异步准备
            mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
    }
}
